package reesoft.common.util;

import java.util.regex.Pattern;

/**
 * 公用正则表达式单元
 *
 * Created by reesoft on 2017-07-14
 */
public class RegexUtil
{
    private static final String ENGLISH = "^[A-Za-z]{1,%d}$";
    private static final String CHINESE = "^[\u4e00-\u9fa5]{1,%d}$";
    private static final String FIGURE = "^[0-9]{1,%d}$";
    private static final String ECF = "^[A-Za-z0-9\u4e00-\u9fa5]{1,%d}$";// 数字、英文字母（不区分大小写）和中文的混合内容
    private static final Pattern EMAIL_PATTERN = Pattern.compile("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$");
    private static final String DEFAULT_MOBILE_PHONE_PATTERN = "^(0|86|17951)?(13[0-9]|15[012356789]|17[06789]|18[0-9]|14[57])[0-9]{8}$";// 手机号码格式
    private static Pattern mobilePhonePattern = Pattern.compile(DEFAULT_MOBILE_PHONE_PATTERN);
    private static final Integer mobilePhonePatternLock = 0;

    /**
     * 判断字符串是否全部由英文字母组成
     */
    public static boolean isEnglish(final String content)
    {
        return Pattern.matches(format(ENGLISH, content), content);
    }

    /**
     * 判断字符串是否全部由汉字组成
     */
    public static boolean isChinese(final String content)
    {
        return Pattern.matches(format(CHINESE, content), content);
    }

    /**
     * 判断字符串是否全部由数字组成
     */
    public static boolean isFigure(final String content)
    {
        return Pattern.matches(format(FIGURE, content), content);
    }

    /**
     * 判断字符串是否全部由数字和中英文字符组成
     */
    public static boolean isEcfCombination(final String content)
    {
        return Pattern.matches(format(ECF, content), content);
    }

    /**
     * 判断邮箱地址是否合法
     */
    public static boolean isEmailAddress(final String content)
    {
        return EMAIL_PATTERN.matcher(content).find();
    }

    /**
     * 设置手机号码格式正则表达式，替换缺省格式
     */
    public static void setMobilePhonePattern(final String pattern)
    {
        if (!StringUtil.isBlank(pattern))
        {
            synchronized (mobilePhonePatternLock)
            {
                mobilePhonePattern = Pattern.compile(pattern);
            }
        }
    }

    /**
     * 判断字符串是否符合手机号码格式
     */
    public static boolean isMobilePhoneNumber(final String content)
    {
        synchronized (mobilePhonePatternLock)
        {
            return mobilePhonePattern.matcher(content).find();
        }
    }

    /**
     * 根据当前参数的位数动态改变字符串匹配的长度
     */
    private static String format(final String regex, final String content)
    {
        return String.format(regex, content.length());
    }
}
